home *** CD-ROM | disk | FTP | other *** search
- Path: hubcap.clemson.edu!hubcap!mjs
- From: mjs@hubcap.clemson.edu (M. J. Saltzman)
- Newsgroups: comp.lang.c
- Subject: Re: Newbie: How to return Multi-Dimensional Array's?
- Date: 7 Feb 96 14:53:14 GMT
- Organization: Clemson University
- Message-ID: <mjs.823704794@hubcap>
- References: <4f7t4m$4bk@news.xs4all.nl> <3118B3F7.2781E494@nada.kth.se>
- NNTP-Posting-Host: hubcap.clemson.edu
-
- Fredrik Rubensson <prgp-fru@nada.kth.se> writes:
-
- >Anthony Moendir wrote:
- >>
- >> How can you return Multi-Dimensional Array's from a function?
-
- You can't return an array of any sort from a function (except as a
- field in a struct). But you can return a pointer to an array (see
- below).
-
- >> I would like to do something like this:
- >>
- >> void main()
- ^^^^
- The keyword that belongs here is spelled "int".
-
- >> {
- >> char arr[10][5];
- >> tmp=foo();
-
- return 0;
-
- >> }
-
- >I don't understand the declaration of arr in main. If you want foo and
- >main to know about arr you shall declare it before main.
-
- But he may not want that. Clearly this isn't a complete code fragment
- (for example, he needs to declare tmp, and arr and tmp are never
- used). As long as he understands that the declaration in foo() is of an
- object different from the one in main(), he's OK here.
-
- >> char *foo()
-
- You need to declare foo before you use it in main. As it is written,
- the compiler will assume that foo() returns an int, which is wrong.
-
- >> {
- >> char arr[10][5];
-
- You should never return the address of an automatic variable. Either
- move the declaration of arr outside the function (which makes it global)
- or declare it static (which keeps its scope inside foo(), but makes it
- outlive the execution of foo()).
-
- >> // do something
-
- C comments are delimited by /* ... */
-
- >> return (arr)
- >> }
-
- >A multidimensional char-array is represented as an array of
- >char-pointers so the return type of foo should be char**.
-
- No, a multidimensional char array is an array of char *arrays*, so
- the return type of foo() (and incidentally the type of tmp in main())
- should be char (*)[5] (pointer to array of 5 chars).
-
- char (*foo())[5]; /* function returning pointer to array of 5 chars */
-
- int main()
- {
- char arr[10][5];
- char (*tmp)[5] = foo(); /* pointer to array of 5 chars */
-
- /* do something, presumably */
-
- return 0;
- }
-
- char (*foo())[5]
- {
- static char arr[10][5]; /* static so address can be used outside */
-
- /* do something */
-
- return arr; /* arr decays to a pointer to its first element
- (an array of 5 chars) */
- }
-
- > The
- >parenthesis around arr after return are not needed.
-
- But a semicolon *is* needed...
- --
- Matthew Saltzman
- Clemson University Math Sciences
- mjs@clemson.edu
-